<?php
namespace app\common\service;

use app\common\logic\UsersLogic;
use think\facade\Db;

/**
 * @author macheng
 * @group name=WxAppLogin,description=微信小程序登录
 */
class Login extends Base
{
    static $AUTH_CHECK = false;

    //账号密码登录
    public function login(){
        $args = input();
        $username = $args['mobile']??'';
        $password = $args['password']??'';
        $user = Db::name('users')->where('username', $username)->field('user_id,username,password,is_lock')->find();
        if (!$user || encrypt($password) != $user['password']) {
            $result = [
                'status' => false,
                'msg' => '账号和密码错误'
            ];
            return $result;
        }
        if($user['is_lock']){
            $result = [
                'status' => false,
                'msg' => '账号已锁定，请联系管理员'
            ];
            return $result;
        }
        $token = logic('UsersLogic')->loginSuccess($user);

        //返回用户信息
        $ret = Db::name('users')->where('user_id', $user['user_id'])->field('user_id,username,head_pic,mobile')->find();

        // guid更新
        $ret['token'] = $token;
        $result = [
            'status' => true,
            'msg' => '登录成功',
            'data' => $ret
        ];

        return $result;
    }
    /**
     * @description 获取绑定信息或互联信息
     * @param string $code 临时登录凭证
     * @param string encryptedData 加密的用户数据 可选
     * @param string iv 加密用数据 可选
     * @return array
     * @return_format  string guid app会员登录唯一标识(已绑定时返回)
     */
    public function index()
    {
        static $AUTH_CHECK = false; //默认必须登录
        $args = input();
        $username = $args['username']??'';
        $password = $args['password']??'';
//        if(!empty($username) && !empty($password)){
//            $rs = Db::name('users')->where('username', $username)->field('user_id,username,password,is_lock')->find();
//            if (encrypt($password) != $rs['password']) {
//                $result = [
//                    'status' => false,
//                    'msg' => '账号和密码错误'
//                ];
//                return $result;
//            }
//            if($rs['is_lock']){
//                $result = [
//                    'status' => false,
//                    'msg' => '账号已锁定，请联系管理员'
//                ];
//                return $result;
//            }
//            $token = logic('UsersLogic')->loginSuccess($rs);
//
//            //返回用户信息
//            $ret = Db::name('users')->where('user_id', $rs['user_id'])->field('user_id,username,head_pic,mobile')->find();
//
//            // guid更新
//            $ret['token'] = $token;
//            $result = [
//                'status' => true,
//                'msg' => '',
//                'data' => $ret
//            ];
//            return $result;
//        }


        $args = input();
        //参数code
        $code = input('code');
        if(!$code) {
            $result = [
                'status' => false,
                'msg' => '参数无效'
            ];
            return $result;
        }


            // 从“微信服务器”获取session_key和open_id
            $appid = tpcache('weixin.wx_app_appid');
            $secret = tpcache('weixin.wx_app_secret');
            if(!$appid || !$secret) {

                $result = [
                    'status' => false,
                    'msg' => '没有配置小程序！请联系管理员！'
                ];
                return $result;
            }
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
            $re = curl_get($url);

            \think\Log::record('WxAppLogin 获取session_key', 'error');
            \think\Log::record($re, 'error');

            $re = json_decode($re, true);
            if(!is_array($re) || !isset($re['openid'])) {
                $errmsg = $re['errmsg'] ?? "";
                $errmsg = "[$code][$errmsg]";
                //abort(500, $errmsg);
                $result = [
                    'status' => false,
                    'msg' => $errmsg
                ];
                return $result;
            }

        $sessionKey = $re['session_key'] ?? '';

        $encryptedData = $args['encryptedData'] ?? '';
        $iv = $args['iv'] ?? '';
        $unionid = '';
        if($sessionKey && $encryptedData && $iv) {
            $data = [];
            $rs = logic('WxApp')->decryptData($encryptedData, $iv, $sessionKey, $data);
            if(!$rs && !empty($data['unionId'])) {
                $unionid = $data['unionId'];
            }
        }

        //不能从微信获取unionid时，从加密参数中解析
        if(empty($re['unionid'])) {
            $re['unionid'] = $unionid;
        }



        //用户资料
        $rawData = input('rawData');
        $rawData_arr = json_decode(htmlspecialchars_decode($rawData,ENT_COMPAT), true);
        $nickname = $rawData_arr['nickName'] ?? input('nickname') ?: ''; //昵称
        $logo = $rawData_arr['avatarUrl'] ?? input('logo') ?: ''; //头像
        $sex = $rawData_arr['gender'] ?? input('sex') ?: 0; //性别

        //签名 验签失败
        /*$signature = $this->params('signature');
        $signature1 = sha1($rawData.$re['session_key']);
        if($signature != $signature1) {
            abort(500,lang('小程序签名失败'));
        }*/

        //是否绑定
        $type = 'weixin';
        $user = logic('SocialLogin')->getBindStatus($type, $re, true);

        if($user) {
            if($username && $username!=$user['username']){
                //当前登录账号和微信已绑定账号不同
                Db::startTrans();
                //解绑微信已绑定账号
                Db::name('social')->where(['user_id' => $user['user_id']])->delete();
                //绑定日志
                Db::name('social_log')->insert(['user_id' => $user['user_id'], 'description' => '切换登录解绑', 'w_time' => getCurTime()]);
                //解绑输入的账号
                //解绑微信已绑定账号
                $now_user = Db::name('users')->where('username',$username)->find();
                Db::name('social')->where(['user_id' => $now_user['user_id']])->delete();
                //绑定日志
                Db::name('social_log')->insert(['user_id' => $now_user['user_id'], 'description' => '切换登录解绑', 'w_time' => getCurTime()]);

                //绑定当前输入的账号
                $token = [];
                $token['openid'] = $re['openid']; //openid
                $token['unionid'] = $re['unionid'] ?? ''; //若有unionid
                $social = [];
                $social['nickname'] = $nickname;
                $social['logo'] = $logo;
                $social['sex'] = $sex ? 1 : 0;
                $user = logic('SocialLogin')->bindUser($username, $type, $token, $social, true, $appid);
                if(!$user['status']){
                    return $user;
                }
                $user['user_id'] = $now_user['user_id'];
                Db::commit();

            }else{
                //更新openid
                $app_openid = Db::name('social')->where(['user_id' => $user['user_id']])->value('app_openid');
                if(!$app_openid) {
                    Db::name('social')->where(['user_id' => $user['user_id']])->setField('app_openid', $re['openid']);
                }
            }

        } else {
            Db::startTrans();
            //已有账号绑定
            if(!empty($args['username'])){
                $username = $args['username'];
                $password = $args['password'];
                $rs = M('users')->where('username', $username)->field('user_id,username,password,is_lock')->find();
                if (encrypt($password) != $rs['password']) {
                    $result = [
                        'status' => false,
                        'msg' => '账号和密码错误'
                    ];
                    return $result;
                }
                if($rs['is_lock']){
                    $result = [
                        'status' => false,
                        'msg' => '账号已锁定，请联系管理员'
                    ];
                    return $result;
                }
            }else{
//                //新建用户
//                $data = [];
//                $data['username'] = logic('User')->getNewUsername(); //获取新编号
//                $data['passwd_one'] = $data['username']; //密码
//                $data['mobile'] = ''; //手机号
//                $data['nickname'] = $nickname;
                $rs = logic('UsersLogic')->createUser();
                $username = $rs['username'];
            }


            //解绑输入的账号
            //解绑微信已绑定账号
            $now_user = Db::name('users')->where('username',$username)->find();
            Db::name('social')->where(['user_id' => $now_user['user_id']])->delete();
            //绑定日志
            Db::name('social_log')->insert(['user_id' => $now_user['user_id'], 'description' => '切换登录解绑', 'w_time' => getCurTime()]);
            //绑定到social表
            $token = [];
            $token['openid'] = $re['openid']; //openid
            $token['unionid'] = $re['unionid'] ?? ''; //若有unionid
            $social = [];
            $social['nickname'] = $nickname;
            $social['logo'] = $logo;
            $social['sex'] = $sex ? 1 : 0;
            $user = logic('SocialLogin')->bindUser($rs['username'], $type, $token, $social, true, $appid);
            Db::commit();
            $user['user_id'] = $user['id'];
        }

        //用户自动登录
        $user['id'] = $user['user_id'];
        $token = logic('UsersLogic')->loginSuccess($user);

        //返回用户信息
        $ret = Db::name('users')->where('user_id', $user['user_id'])->field('user_id,username,head_pic,mobile')->find();

        // guid更新
        $ret['token'] = $token;
        $result = [
            'status' => true,
            'msg' => '',
            'data' => $ret
        ];

        return $result;
    }

    public function bindMobile(){

        $args = input();
        //参数code
        $code = input('code');
        $appid = tpcache('weixin.wx_app_appid');
        $secret = tpcache('weixin.wx_app_secret');

        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
        $re = curl_get($url);
        $re = json_decode($re,true);

        $access_token = $re['access_token'];

        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$access_token;
        $phone_res = curl_post($url,json_encode(['code'=>$code]));
        $phone_res = json_decode($phone_res,true);
        $mobile = $phone_res['phone_info']['phoneNumber'];
        $user_id = input('user_id');
        Db::name('users')->where('user_id',$user_id)->setField('mobile',$mobile);
        $result = [
            'status' => true,
            'msg' => '',
            'data' => '',
        ];

        return $result;



        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$code.'&grant_type=authorization_code';
        $re = curl_get($url);
        $sessionKey = $re['session_key'] ?? '';
        $encryptedData = $args['encryptedData'] ?? '';
        $iv = $args['iv'] ?? '';
        $data = [];
        if($sessionKey && $encryptedData && $iv) {
            $rs = logic('WxApp')->decryptData($encryptedData, $iv, $sessionKey, $data);
        }
        $result = [
            'status' => true,
            'msg' => '',
            'data' => $data,
            'phone_res'=>$phone_res
        ];

        return $result;
    }

    //手机号注册
    public function regsub(){
        $mobile = input('mobile');
        $password = input('pwd');
        $intro = input('intro');
        $pid = input('pid');
        if(!$intro && $pid ){
            $intro = Db::name('users')->where('user_id',$pid)->value('username');
        }
        if(!$intro){
            return [
                'status' => 0,
                'msg' => '请填写邀请码',
            ];
        }
        $username = input('username');
        Db::startTrans();
        $user = logic('UsersLogic')->createuser($mobile,$password,$intro,$username);
        $status = 0;
        $msg = $user['msg']??'注册成功';
        if($user['status']){
            $status = 1;
            $token = logic('UsersLogic')->loginSuccess($user);
            $user['token'] = $token;
        }

        Db::commit();
        return [
            'status' => $status,
            'msg' => $msg,
            'data' => $user
        ];
    }


    //微信小程序授权登录
    public function wxlogin(){


        $shopset = self::$shop_set;

        $jscode = input('code');
        $loginmsg = '登录成功';
        $params = input();
        $userinfo = $params['userinfo']??'';
        if(empty($userinfo)){
            $userinfo = [
                'nickName'=>'微信用户',
                'avatarUrl'=> '',
                'gender'=> 0,
                'province'=> '',
                'city'=> ''
            ];
        }


        $fromid = input('param.pid');
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$shopset['appid'].'&secret='.$shopset['appsecret'].'&js_code='.$jscode.'&grant_type=authorization_code';
        $rs = curlGet($url);
        $rs = json_decode($rs,true);
        if(!empty($rs['errcode']) && $rs['errcode']>0){
            $err_msg = logic('WechatLogic')->geterror($rs);
            return ['status'=>0,'msg'=>$err_msg];
        }
        $openid = $rs['openid'];
        if(!$openid) return json(['status'=>0,'msg'=>'获取授权信息失败']);
        $unionid = $rs['unionid']??'';
        $session_key = $rs['session_key'];
        $social = Db::name('social')->where('wxapp_openid',$openid)->find();
        if(!$social && $unionid){
            $social = Db::name('social')->where('unionid',$unionid)->find();
            if($social) Db::name('social')->where('id',$social['id'])->update(['wxapp_openid'=>$openid]);
        }
        if(!$social){
            $rs['userinfo'] = $userinfo;

            if($shopset['login_setnickname'] && (!$userinfo['nickName'] || $userinfo['nickName'] == '微信用户')){
                return ['status'=>3,'msg'=>'设置头像昵称','login_setnickname'=>$shopset['login_setnickname'],'login_bind'=>$shopset['login_bind'],'openid'=>$openid,'unionid'=>$unionid];
            }
            if($shopset['login_bind']){
                return ['status'=>2,'msg'=>'绑定手机号','login_bind'=>$shopset['login_bind'],'openid'=>$openid,'unionid'=>$unionid];
            }

            return $this->wxRegister($rs);
        }else{
            $uid = $social['user_id'];
            $user = Db::name('users')->where('user_id',$uid)->find();
            if( ($user['nickname'] == '微信用户' || $user['nickname'] == '关注用户')){
                $rs['userinfo'] = $userinfo;
                return ['status'=>3,'msg'=>'设置头像昵称','login_setnickname'=>$shopset['login_setnickname'],'login_bind'=>$shopset['login_bind']
                    ,'openid'=>$social['wxapp_openid'],'unionid'=>$social['unionid']
                ];
            }
//            $update = [];
//            $update['head_pic'] = $userinfo['avatarUrl'];
//            $update['nickname'] = $userinfo['nickName'];
//            $update['sex'] = $userinfo['gender'];
//            $update['province'] = $userinfo['province'];
//            $update['city'] = $userinfo['city'];
//            Db::name('users')->where('user_id',$user['user_id'])->update($update);

            //更新session信息
            if($shopset['login_bind'] && empty($user['mobile'])){
                $rs['userinfo'] = $userinfo;
                return [
                    'status'=>2,'msg'=>'绑定手机号','login_bind'=>$shopset['login_bind']
                    ,'openid'=>$social['wxapp_openid'],'unionid'=>$social['unionid']
                ];
            }
        }
        $token = logic('UsersLogic')->loginSuccess($user);
        //返回用户信息
        $ret = Db::name('users')->where('user_id', $user['user_id'])->field('user_id,username,head_pic,mobile')->find();
        // guid更新
        $ret['token'] = $token;
        $result = [
            'status' => 1,
            'msg' => '登录成功',
            'mid' => $uid,
            'token' => $token,
            'data' => $ret
        ];

        return $result;
    }

    public function wxRegister($rs=''){
        $shopset = self::$shop_set;
        $user = [];
        if($rs){
            //wxlogin直接调用过来的
            $userinfo = $rs['userinfo'];
            $authlogin = $rs['authlogin']??0;
            $fromid = input('pid');
            if($rs['errcode']>0){
                $err_msg = logic('WechatLogic')->geterror($rs);
                return ['status'=>0,'msg'=>$err_msg];
            }
            $openid = $rs['openid'];
            if(!$openid) return json(['status'=>0,'msg'=>'获取授权信息失败']);
            $unionid = $rs['unionid'];
            $session_key = $rs['session_key'];
        }else{
            //wxlogin判断到需要绑定手机号或昵称之后又再下一步传过来的
            $openid = input('openid')?:'';
            $unionid = input('unionid')?:'';

        }
        if($openid || $unionid){
            $social = Db::name('social')->where('wxapp_openid',$openid)->find();
            if(!$social && $unionid){
                $social = Db::name('social')->where('unionid',$unionid)->find();
                if($social) Db::name('social')->where('id',$social['id'])->update(['wxapp_openid'=>$openid]);
            }
            if($social){
                $user = Db::name('users')->where('user_id',$social['user_id'])->find();
            }
        }

        $nickname = input('nickname');
        $logo = input('headimg');
        $tel = '';
        if(input('code') && input('iv') && input('encryptedData')){
            //授权获取手机号或昵称传过来的
            $jscode = input('code');
            $encryptedData = input('encryptedData');
            $iv = input('post.iv');
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$shopset['appid'].'&secret='.$shopset['appsecret'].'&js_code='.$jscode.'&grant_type=authorization_code';
            $rs = curlGet($url);
            $rs = json_decode($rs,true);
            if($rs['errcode']>0){
                $err_msg = logic('WechatLogic')->geterror($rs);
                return ['status'=>0,'msg'=>$err_msg];
            }
            $session_key = $rs['session_key'];
            if(!$session_key) return json(['status'=>0,'msg'=>'获取授权信息失败']);
            $rdata = [];
            $errCode = logic('WxApp')->decryptData($encryptedData, $iv, $session_key, $rdata);
            $openid = $rs['openid'];
            $unionid = $rs['unionid'];
            if($rdata['phoneNumber']){
                $tel = $rdata['phoneNumber'];
            }else{
                return json(['status'=>0,'msg'=>'授权获取手机号失败']);
            }
        }elseif(input('param.tel')){
            $tel = input('param.tel');
            $smscode = input('param.smscode');
            if(md5($tel.'-'.$smscode) != cache($this->sessionid.'_smscode') || cache($this->sessionid.'_smscodetimes')>5){
                cache($this->sessionid.'_smscodetimes',cache($this->sessionid.'_smscodetimes')+1);
                return ['status'=>0,'msg'=>'短信验证码错误'];
            }
            cache($this->sessionid.'_smscode',null);
            cache($this->sessionid.'_smscodetimes',null);
        }
        if($tel){
            if($user){
                $hasuser = Db::name('users')->where(['mobile'=>$tel,'user_id'=>['neq',$user['user_id']]])->find();
                if(!$hasuser){
                    Db::name('users')->where('id',$user['user_id'])->update(['mobile'=>$tel]);
                }else{
                    return ['status'=>0,'msg'=>'该手机号已被其他用户绑定'];
                }
            }else{
                $user = Db::name('users')->where('mobile',$tel)->find();
                if($user){
                    $update = [];
                    $update['wxapp_openid'] = $openid;
                    if($unionid){
                        $update['unionid'] = $unionid;
                    }
                    Db::name('users')->where('id',$user['id'])->update($update);
                }
            }
        }
        if(!empty($user) && input('nickname')){
            $update = [];
            $update['head_pic'] = input('headimg');
            $update['nickname'] = input('nickname');
            Db::name('users')->where('user_id',$user['user_id'])->update($update);
        }
        if(empty($user)){
            Db::startTrans();
            $intro = '';
            if(input('pid')){
                $intro = Db::name('users')->where('user_id',input('pid'))->value('username');
            }
            $rs_user = logic('UsersLogic')->createUser($tel,'123456',$intro);
            $username = $rs_user['username'];
            //绑定到social表
            $token = [];
            $token['openid'] = $openid??''; //openid
            $token['unionid'] = $unionid ?? ''; //若有unionid
            $social = [];
            $social['nickname'] = $nickname;
            $social['logo'] = $logo;
            $social['sex'] = 1;
            $user = logic('SocialLogin')->bindUser($username, 'wxapp', $token, $social, true, $shopset['appid']);
            if(empty($user['status'])){
                return $user;
            }
            Db::commit();
        }
        $token = logic('UsersLogic')->loginSuccess($user);
        //返回用户信息
        $ret = Db::name('users')->where('user_id', $user['user_id'])->field('user_id,username,head_pic,mobile')->find();
        // guid更新
        $ret['token'] = $token;
        $result = [
            'status' => 1,
            'msg' => '登录成功',
            'mid' => $user['user_id'],
            'token' => $token,
            'data' => $ret
        ];

        return $result;
    }

    public function sendsms(){
        $mobile = input('tel');
        $username = input('username');
        $exit = Db::name('users')->where('username',$username)->where('mobile',$mobile)->find();
        if(!$exit){
            $result = [
                'status' => 0,
                'msg' => '账号不存在！'
            ];
            return $result;
        }
        $res = logic('SmsLogic')->sendSms('find_sms',$mobile,$username);
        writeLog(json_encode($res,JSON_UNESCAPED_UNICODE),'sms');
        if(!$res['status']){
            return $res;
        }
        $result = [
            'status' => 1,
            'msg' => '发送成功！'
        ];
        return $result;
    }

    //app微信登录
    public function appwxlogin(){
        $jscode = input('param.code');
        $fromid = input('param.pid');
        $app = \app\common\System::appinfo(aid,'app');

        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$app['appid'].'&secret='.$app['appsecret'].'&code='.$jscode.'&grant_type=authorization_code';
        $rs = request_get($url);
        $rs = json_decode($rs,true);
        if($rs['errcode']>0){
            return ['status'=>0,'msg'=>\app\common\Wechat::geterror($rs)];
        }
        $openid = $rs['openid'];
        if(!$openid){
            return ['status'=>0,'msg'=>'获取授权信息失败'];
        }
        $unionid = $rs['unionid'];
        $access_token = $rs['access_token'];

        $users = Db::name('users')->where('appopenid',$openid)->find();
        if(!$users && $unionid){
            $users = Db::name('users')->where('unionid',$unionid)->find();
            if($users) Db::name('users')->where('id',$users['id'])->update(['appopenid'=>$openid]);
        }
        if(!$users){
            $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
            $result = request_get($url);
            $result = json_decode($result,true);
            if($result['errcode']>0){
                return ['status'=>0,'msg'=>\app\common\Wechat::geterror($result)];
            }

            cache($this->sessionid.'_'.platform.'UserInfo',$result,3600);
            $info = Db::name('admin_set')->where('aid',aid)->find();
            if($info['login_bind']) {
                return $this->json(['status'=>2,'msg'=>'绑定手机号','login_bind'=>$info['login_bind']]);
            }
            return $this->appwxRegister();
        }else{
            $mid = $users['id'];

            if(!$users['headimg'] || strpos($users['headimg'],'/static/img/touxiang.png') !== false){
                $update = [];
                $update['headimg'] = \app\common\Pic::uploadoss($result['headimgurl']);
                $update['nickname'] = $result['nickname'];
                $update['sex'] = $result['sex'];
                $update['province'] = $result['province'];
                $update['city'] = $result['city'];
                Db::name('users')->where('id',$users['id'])->update($update);
            }
        }
        $token = logic('UsersLogic')->loginSuccess($users);
        //返回用户信息
        $ret = Db::name('users')->where('user_id', $users['user_id'])->field('user_id,username,head_pic,mobile')->find();
        // guid更新
        $ret['token'] = $token;
        $result = [
            'status' => 1,
            'msg' => '登录成功',
            'mid' => $users['id'],
            'token' => $token,
            'data' => $ret
        ];
        return $result;
    }

    //app微信注册
    public function appwxRegister(){
        $fromid = input('param.pid');
        $tel = input('param.tel');
        $smscode = input('param.smscode');
        $result = cache($this->sessionid.'_'.platform.'UserInfo');
        $openid = $result['openid'];
        if(!$openid){
            return ['status'=>0,'msg'=>'获取授权信息失败'];
        }
        $unionid = $result['unionid'];
        $access_token = $result['access_token'];

        $users = Db::name('users')->where('aid',aid)->where('appopenid',$openid)->find();
        if(!$users && $unionid){
            $users = Db::name('users')->where('unionid',$unionid)->find();
            if($users) Db::name('users')->where('user_id',$users['user_id'])->update(['appopenid'=>$openid]);
        }
        if($tel){
            if($users){
                $hasmember = Db::name('users')->where('tel',$tel)->find();
                if(!$hasmember){
                    Db::name('users')->where('user_id',$users['id'])->update(['tel'=>$tel]);
                }else{
                    return ['status'=>0,'msg'=>'该手机号已被其他用户绑定'];
                }
            }else{
                $users = Db::name('users')->where('tel',$tel)->find();
                if($users){
                    $update = [];
                    $update['appopenid'] = $openid;
                    if($unionid){
                        $update['unionid'] = $unionid;
                    }
                    if(!$users['headimg'] || strpos($users['headimg'],'/static/img/touxiang.png') !== false){
                        $update['headimg'] = \app\common\Pic::uploadoss($result['headimgurl']);
                        $update['nickname'] = $result['nickname'];
                        $update['sex'] = $result['sex'];
                        $update['province'] = $result['province'];
                        $update['city'] = $result['city'];
                    }
                    Db::name('users')->where('user_id',$users['user_id'])->update($update);
                }
            }
        }
        if(!$users){
            if($result['errcode']>0){
                return $this->json(['status'=>0,'msg'=>\app\common\Wechat::geterror($result)]);
            }
            $data = [];
            $data['appopenid'] = $openid;
            if($unionid){
                $data['unionid'] = $unionid;
            }
            $data['nickname'] = $result['nickname'];
            $data['sex'] = $result['sex'];
            $data['province'] = $result['province'];
            $data['city'] = $result['city'];
            $data['country'] = $result['country'];
            $data['headimg'] = \app\common\Pic::uploadoss($result['headimgurl']);

//            $data['session_id'] = $this->sessionid;
            $data['createtime'] = time();
            $data['last_visittime'] = time();
            if($tel){
                $data['tel'] = $tel;
            }
            //推广人
            if($fromid){
                $data['pid'] = $this->getpid($fromid);
            }
            $data['platform'] = platform;
            $mid = \app\model\Member::add(aid,$data);
            Db::name('session')->where('aid',aid)->where('session_id',$this->sessionid)->update([
                'mid' => $mid,
                'login_time' => time()
            ]);
            if($data['pid']) \app\common\Common::user_tjscore(aid,$mid);
            //注册赠送
            \app\common\Common::registerGive(aid,array_merge($data, ['id' => $mid]));
        }else{
            $mid = $users['id'];
        }
        $token = logic('UsersLogic')->loginSuccess($users);
        //返回用户信息
        $ret = Db::name('users')->where('user_id', $users['user_id'])->field('user_id,username,head_pic,mobile')->find();
        // guid更新
        $ret['token'] = $token;
        $result = [
            'status' => 1,
            'msg' => '登录成功',
            'mid' => $users['id'],
            'token' => $token,
            'data' => $ret
        ];
        return $result;
    }

    //找回密码
    public function getpwd(){
        if(request()->isPost()){
            $username = input('param.username');
            $tel = input('param.tel');
            $pwd = input('param.pwd');
            $smscode = input('param.smscode');
            $map = [];
            $map['username'] = $username;
            $map['mobile'] = $tel;
            $map['status'] = 0;
            $exit_smscode = Db::name("send_sms")->where($map)->order('id desc')->find();
            if(!$exit_smscode || $exit_smscode['codes']!=$smscode){
                return ['status'=>0,'msg'=>'短信验证码错误'];
            }
            $map = [];
            $map['username'] = $username;
            $map['mobile'] = $tel;
            $user = Db::name('users')->where($map)->find();
            if(!$user){
                return ['status'=>0,'msg'=>'该手机号或登录账号不存在'];
            }
            Db::name('users')->where($map)->update(['password'=>encrypt($pwd)]);
            Db::name("send_sms")->where('id',$exit_smscode['id'])->update(['status'=>1]);
            return ['status'=>1,'msg'=>'重置成功'];
        }else{
            $rdata = [];
            $rdata['status'] = 1;


            return $rdata;
        }

    }

}







